import 'dart:developer';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html_table/flutter_html_table.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/home/inner_video/html_video.dart';
import 'package:ball_lion/entity/home/news_item_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/picture_preview_widget.dart';
import 'package:ball_lion/widgets/player/qs_player_logic.dart';
import 'package:ball_lion/widgets/html/wqs_fee.dart';
import '../base/wqs_image.dart';
import '../base/wqs_text.dart';

class QsHtml extends StatefulWidget {
  const QsHtml({
    super.key,
    required this.data,
    this.matchLabel,
    this.disclaimer,
    this.mediaFrom,
    this.id,
    this.player,
    this.margin,
    this.showFeeLine,
  });

  final String data;
  final List<HrefItem>? matchLabel;
  final String? disclaimer;
  final String? mediaFrom;
  final int? id;
  final QsPlayerLogic? player;
  final Margins? margin;
  final bool? showFeeLine;

  @override
  State<QsHtml> createState() => _QsHtmlState();
}

class _QsHtmlState extends State<QsHtml> {
  @override
  Widget build(BuildContext context) {
    return Html(
      shrinkWrap: true,
      data: getData(),
      extensions: [
        const TableHtmlExtension(),
        if (widget.player != null && widget.id != null)
          InnerVideoExtension(id: widget.id!, logic: widget.player!),
        TagExtension(
            tagsToExtend: {"img"},
            builder: (extensionContext) {
              final e = extensionContext.styledElement;
              return GestureDetector(
                onTap: () => Get.dialog(
                    PicturePreview(imageUrl: e?.attributes['src'] ?? ""),
                    useSafeArea: false),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: CachedNetworkImage(
                    imageUrl: e?.attributes['src'] ?? "",
                    width: Get.width,
                    fit: BoxFit.cover,
                    placeholder: (context, url) => Container(),
                    errorWidget: (context, url, error) => Container(),
                  ),
                ),
              );
            }),
        TagExtension(
            tagsToExtend: {"matchlabel"},
            builder: (extensionContext) {
              return Wrap(
                      spacing: 8,
                      runSpacing: 8,
                      children: widget.matchLabel
                              ?.map((e) => richLabelCell(e))
                              .toList() ??
                          [])
                  .paddingOnly(bottom: 24);
            }),
        TagExtension(
            tagsToExtend: {"feeline"},
            builder: (extensionContext) {
              return widget.showFeeLine == true
                  ? FeeLine(extensionContext: extensionContext)
                  : Container();
            }),
      ],
      onLinkTap: (url, attributes, element) {
        if (url?.contains("http") == true) return;
        Utils.doJump(url?.replaceAll("\u200A", "") ?? "");
      },
      style: {
        "html": Style(margin: Margins.zero, padding: HtmlPaddings.zero),
        "body": Style(letterSpacing: -0.5),
        "p": Style(margin: Margins.only(bottom: 16)),
        "matchLabel": Style(margin: Margins.all(0)),
        "a": Style(
            color: Colours.blue2766D6, textDecoration: TextDecoration.none),
        "img": Style(
            width: Width(Get.width - 40),
            margin: Margins.only(bottom: 16),
            display: Display.block,
            textAlign: TextAlign.center),
        ".content": Style(
            padding: HtmlPaddings.zero,
            // backgroundColor: Colors.green,
            margin: Margins.zero),
        "#wholeBody": Style(
            margin: widget.margin ??
                Margins.only(left: 20, right: 20, top: 8, bottom: 6)),
        "#publishInfo": Style(
            fontSize: FontSize(14),
            color: Colours.grey99,
            textAlign: TextAlign.left,
            margin: Margins.only(top: 8)),
        "#article": Style(
            color: Colours.text,
            margin: Margins.all(0),
            fontSize: FontSize(18),
            letterSpacing: -0.6,
            lineHeight: const LineHeight(1.6),
            whiteSpace: WhiteSpace.normal,
            textAlign: TextAlign.justify),
        "#reprint": Style(
            fontSize: FontSize(12),
            // backgroundColor: Colors.brown,
            color: Colours.grey99,
            textAlign: TextAlign.justify,
            fontWeight: FontWeight.w300,
            margin: Margins.only(bottom: 8)),
        "#claim": Style(
            fontSize: FontSize(12),
            // backgroundColor: Colors.pinkAccent,
            color: Colours.grey99,
            lineHeight: const LineHeight(1.4),
            textAlign: TextAlign.justify,
            fontWeight: FontWeight.w300),
        ".teamInfo":
            Style(fontWeight: FontWeight.w500, margin: Margins.only(bottom: 4))
      },
    );
  }

  String getData() {
    var regC = RegExp(r"[\u4e00-\u9fa5]");
    var regCom = RegExp(r'</p>[.\n\s]*<p>');
    var regP = RegExp(r'/>[.\n\s]*<p>');
    var regImg = RegExp(r'/>[.\n\s]*<img');
    var regInLine = RegExp(r'<p[^<>]*>[^<>]+<img');
    String append = '';
    String? com = widget.data.splitMapJoin(regInLine, onMatch: (match) {
      var result = match[0]?.split("<img").join("</p><p><img") ?? "";
      return result;
    });
    // .split(RegExp(r"<[br \/]+>")).join("")
    com = com.replaceAllMapped(
        RegExp(r"<div\s.*?>([\s\S]*?)<\/div>"), (match) => match.group(1)!);
    com = com.replaceAllMapped(RegExp(r"""<span class="img">(.*?)<\/span>"""),
        (match) => match.group(1)!);
    com = com
            .split("<p>&nbsp;</p>")
            .join("<div style= 'height: 8;width: 200px;'>  </div>")
            .split(regCom)
            .join("</p><div style= 'height: 8;width: 200px;'>  </div><p>")
            .split(regP)
            .join("/><div style= 'height: 8;width: 200px;'>  </div><p>")
            .split(regImg)
            .join("/><div style= 'height: 8;width: 200px;'>  </div><img")
            .split('src=" ')
            .join('src="')
        // .split(regBody)
        // .join("/p><div style= 'height: 25;width: 200px;'>  </div></body")
        ??
        "";
    log(com);
    com.split("").forEach((element) {
      if (regC.hasMatch(element)) {
        append += "$element\u200A";
      } else {
        append += element;
      }
    });

    var newData = "";
    newData = "<body id='wholeBody'>"
        "<div id='article'>$append</div>"
        // "<div style= 'height: 24px;width: 200px;'>  </div>"
        "${widget.matchLabel == null ? "" : "<matchlabel> </matchlabel>"}"
        "${widget.mediaFrom.noValue ? '' : "<p id='reprint'>${'转\u200A载\u200A自\u200A：\u200A${widget.mediaFrom?.split('').join("\u200A")}'}</p>"}"
        "${widget.disclaimer.noValue ? "" : "<p id='claim'>${widget.disclaimer?.split('').join("\u200A") ?? ''}</p>"}"
        "</body>";
    return newData;
  }

  Widget userInfoCell(String? logo, String? name, bool reverse) {
    List<Widget> list = [
      QsImage(imageUrl: logo, width: 16, height: 16),
      Container(width: 4),
      QsText(name ?? "", fontSize: 12)
    ];
    if (reverse) list = list.reversed.toList();
    return Row(mainAxisSize: MainAxisSize.min, children: list);
  }

  Widget richLabelCell(HrefItem item) {
    Widget cell = Container();
    switch (item.type) {
      case 1:
        List<String> name = item.name?.split(",") ?? [];
        List<String> logo = item.logo?.split(",") ?? [];
        cell = Row(
          mainAxisSize: MainAxisSize.min,
          children: List.generate(
              2,
              (index) => userInfoCell(
                  logo.length - 1 < index ? "" : logo[index],
                  name.length - 1 < index ? "" : name[index],
                  index == 1)).insertWith(1, [
            Image.asset(width: 16, Utils.getImgPath("news_vs.png"))
                .paddingSymmetric(horizontal: 6)
          ]),
        );
        break;
      default:
        cell = userInfoCell(item.logo, item.name, false);
    }
    return GestureDetector(
      onTap: () {
        switch (item.type) {
          case 1:
            Get.toNamed(Routes.zqMatchDetail, arguments: item.extId);
            break;
          case 2:
            Get.toNamed(Routes.leagueDetail,
                arguments: item.extId.toString(),
                parameters: {"type": "0", "index": "0"});
            break;
          case 3:
            Get.toNamed(Routes.zqTeamDetail, arguments: item.extId);
            break;
        }
      },
      child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          decoration: BoxDecoration(
              color: Colours.greyF7, borderRadius: BorderRadius.circular(4)),
          child: cell),
    );
  }
}
